package com.google.code.coma.space;

import com.google.code.coma.domain.Computer;
import com.google.code.coma.domain.Order;
import com.google.code.coma.domain.Part;
import com.google.code.coma.domain.Type;
import org.mozartspaces.capi3.Capi3Exception;
import org.mozartspaces.capi3.javanative.operation.NativeEntry;

import java.util.ArrayList;
import java.util.Collection;
import java.util.Collections;
import java.util.List;

/**
 * @author Dominik Strasser, dominikstr@gmail.com
 */
public class ApplicableOrderSelectorCallback implements SelectorCallback {
	private Computer computer;

	public ApplicableOrderSelectorCallback(Computer computer) {
		this.computer = computer;
	}

	@Override
	public List<NativeEntry> doInTransaction(Collection<NativeEntry> coordinatorCollection, CallContext callContext) throws Capi3Exception {
		for (final NativeEntry e : coordinatorCollection) {
			if (e.getData() != null && e.getData() instanceof Order) {
				Order order = (Order) e.getData();				
				if (!order.isFinished() && order.getCpuType().equals(getCPUType()) && order.getNumberOfRAMModules() == numberOfRAMs()) {
					return Collections.singletonList(e);
				}
			}
		}
		return new ArrayList<NativeEntry>();
	}

	private String getCPUType() {
		for (Part p : computer.getParts()) {
			if (p.getType() == Type.CPU) {
				return p.getAppellation();
			}
		}
		return null; //shouldn't happen
	}

	private int numberOfRAMs() {
		int sum = 0;
		for (Part p : computer.getParts()) {
			if (p.getType() == Type.RAM) {
				sum++;
			}
		}
		return sum; //shouldn't happen
	}
}
